package cn.sola.redis.thumbs.up;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * @author: kangxiaohui
 * @date：2018年8月29日 上午11:38:50
 * @version 1.0 点赞
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext-redis3.xml")
public class ThumbsUp {

	private final static String DEFAULT_QUESTION_ID = "mls_AnswerIdsByQuersionId:" + 123;

	@Resource(name = "redisTemplate")
	private ZSetOperations<String, Long> zSet;

	@Test
	public void index() {
		System.out.println(zSet);
	}

	@Test
	public void answerQuestion() {
		zSet.add(DEFAULT_QUESTION_ID, 234L, 5); // 添加单条
		zSet.add(DEFAULT_QUESTION_ID, 4565L, 13);
		zSet.add(DEFAULT_QUESTION_ID, 2345L, 15);
		Set<ZSetOperations.TypedTuple<Long>> var2 = new HashSet<>();
		ZSetOperations.TypedTuple<Long> answerVoInZset1 = new DefaultTypedTuple<Long>(2343L, 12.0);
		ZSetOperations.TypedTuple<Long> answerVoInZset2 = new DefaultTypedTuple<Long>(5675L, 16.0);
		ZSetOperations.TypedTuple<Long> answerVoInZset4 = new DefaultTypedTuple<Long>(4562L, 11.0);
		var2.add(answerVoInZset1);
		var2.add(answerVoInZset2);
		var2.add(answerVoInZset4);
		zSet.add(DEFAULT_QUESTION_ID, var2);// 批量添加
		zSet.remove(DEFAULT_QUESTION_ID, 4565L); // 移除单个元素

		Set<Long> ids = zSet.reverseRange(DEFAULT_QUESTION_ID, 0, 3);
		System.out.println(ids);
	}

	/**
	 * 记录
	 * @param userId
	 * @param positionId 每一个回答的id
	 */
	public void addRecentBrowsingPosition(long userId, long positionId) {
		String key = "mls_AnswerIdsByQuersionId:" + 123;
		// 获取已缓存的最近浏览的职位
		// zset内部是按分数来排序的，这里用当前时间做分数
		zSet.add(key, positionId, System.currentTimeMillis());
		// 环形结构--4,-3,-2,-1,0,1,2,3,4
		zSet.removeRange(key, 0, -6);
	}

	public List<Long> getRecentBrowsingPositionIds(long userId) {
		if (userId <= 0) {
			return Collections.emptyList();
		}
		// 获取用户最近浏览的职位id
		Set<Long> positionIds = zSet.reverseRange(DEFAULT_QUESTION_ID, 0, 4);
		return new ArrayList<>(positionIds);
	}
}
